"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { RestEndpointMethodTypes } from "@octokit/plugin-rest-endpoint-methods";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "~/shared/ui/dialog";
import { $api } from "~/shared/api";
import { convertEmoji } from "~/shared/lib/convert-emoji";

import { materialDark as style } from "react-syntax-highlighter/dist/esm/styles/prism";

export default function CommitModal({
  params: { sha },
}: {
  params: { sha: string };
}) {
  const [commit, setCommit] = useState<
    null | RestEndpointMethodTypes["repos"]["getCommit"]["response"]["data"]
  >(null);
  const [loading, setLoading] = useState<boolean>(true);

  const router = useRouter();

  useEffect(() => {
    setLoading(true);
    const fetchCommit = async () => {
      const response = await $api.rest.repos.getCommit({
        owner: "velenyx",
        repo: "github-commit-explorer",
        ref: sha,
      });
      setCommit(response.data);
      setLoading(false);
    };

    fetchCommit();
  }, []);

  const aggregatedDiff =
    commit?.files?.reduce(
      (acc, file) => {
        return acc + (file.patch || ""); // Ensure to handle cases where patch might be undefined
      },
      String.raw``,
    ) || "";

  return (
    <div>
      <Dialog
        open={true}
        onOpenChange={() => {
          router.back();
        }}
      >
        <DialogContent className="h-full max-h-[90vh] max-w-[90vw]">
          {loading ? (
            <h1>Loading...</h1>
          ) : (
            <>
              <DialogHeader>
                <DialogTitle>
                  {convertEmoji(commit!.commit.message)}
                </DialogTitle>
                <DialogDescription>
                  by {commit?.commit.author?.name}
                </DialogDescription>
              </DialogHeader>
              <SyntaxHighlighter showLineNumbers language="diff" style={style}>
                {aggregatedDiff}
              </SyntaxHighlighter>
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
